﻿using DevExpress.XtraBars;
using EyFramework.Common;
using EyFramework.Common.Utils;
using EyFramework.Library;
using Ncov2019.Core.Service;
using Ncov2019.Entity;
using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
using EyFramework.Sys.Core;

namespace Ncov2019
{
    public partial class FrmNcovPat : FrmDevBase
    {
        private List<GridColumnInfo> columnInfos = new List<GridColumnInfo>();

        private INcovUsersService ncovUsersService;

        public FrmNcovPat()
        {
            InitializeComponent();
        }

        private void InitForm()
        {
            DataBinder.BindingLookupEditDataSource(lueRylb, SysCache.GetCacheSysDict(SysConstants.DICT_NCOV_PAT_TYPE, true), "DICT_LABEL", "DICT_VALUE");
            gvData.ShowRowNum();
            gcData.ShowContextMenu(this.components);//显示右键导出功能
            #region
            columnInfos.Add(new GridColumnInfo("CHT_ID", "病历号码", 100));
            columnInfos.Add(new GridColumnInfo("PAT_NM", "姓名", 100));
            columnInfos.Add(new GridColumnInfo("BIRTHDAY", "出生日期", 100));
            columnInfos.Add(new GridColumnInfo("SEX", "性别", 100));
            columnInfos.Add(new GridColumnInfo("ID_NO", "身份证号", 200));
            columnInfos.Add(new GridColumnInfo("TELPHONE", "联系电话", 100));
            columnInfos.Add(new GridColumnInfo("COMPANY", "单位名称", 200));
            columnInfos.Add(new GridColumnInfo("DEPARTMENT", "部门名称", 200));
            columnInfos.Add(new GridColumnInfo("PAT_TYPE", "人员类型", 50));
            columnInfos.Add(new GridColumnInfo("PAT_TAGS", "人员标记", 200));
            #endregion
            DevExpress.XtraGrid.GridFormatRule gfrId = new DevExpress.XtraGrid.GridFormatRule() { Name = "gfrId" };
            // 指定应用到编号列
            gfrId.Column = gvData.Columns["DC_FLAG"];
            gfrId.Rule = new DevExpress.XtraEditors.FormatConditionRuleExpression()
            {
                // 使用Dev默认提供的预定义样式
                PredefinedName = "Red Fill, Red Text",
                Expression = "[DC_FLAG]='1' ", // Id值为奇数
            };
            // 是否应用到整行
            gfrId.ApplyToRow = true;
            this.gvData.FormatRules.Add(gfrId);
        }

        private void FrmNcovLabCollect_Load(object sender, EventArgs e)
        {
            ncovUsersService = EyFramework.Common.Globals.GetService<INcovUsersService>();
            InitForm();
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            ShowLoading();
            btnQuery.Enabled = false;
            try
            {
                QueryData();
                //避免多次重复点击按钮触发多次查询检索,清理掉windows的事件消息
                Application.DoEvents();
                CloseLoading();
                btnQuery.Enabled = true;
            }
            catch
            {
                btnQuery.Enabled = true;
                throw;
            }
        }

        private void QueryData()
        {
            var ncovUsersParam = new NcovUsersParam
            {
                CHT_ID = teChtId.Text.Trim(),
                PAT_NM = tePatNm.Text.Trim(),
                PAT_TYPE = lueRylb.EditValue == null ? "" : lueRylb.EditValue.ToString(),
                DC_FLAG = chkDcFlag.Checked ? "Y" : "N"
            };
            var ncovUsers = ncovUsersService.QueryBy(ncovUsersParam);
            ncovUsers.ForEach(p =>
            {
                p.SEX = SysCache.GetDictVal(p.SEX, SysConstants.DICT_SEX);
                p.PAT_TYPE = SysCache.GetDictVal(p.PAT_TYPE, SysConstants.DICT_NCOV_PAT_TYPE);
            });
            gcData.DataSource = ncovUsers;
            DevPublic.SetGridControlView(gvData, columnInfos, true, true);
        }

        private void bbiImport_ItemClick(object sender, ItemClickEventArgs e)
        {
            ofd.Filter = "*.xls(Excel文件)|*.xls|*.xlsx(Excel文件)|*.xlsx";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                //导入指定的excel模板数据
                DataTable dt = ExcelImporter.ImportByIndex(ofd.FileName);
                ImportUsers(dt);
            }
        }

        public void ImportUsers(DataTable dt)
        {
            var ncovUsers = new List<NcovUsers>();
            if (dt.Rows.Count > 0)
            {
                string checkResult = "";
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    checkResult = CheckExcelRow(dt.Rows[i], i);
                    if (!string.IsNullOrEmpty(checkResult))
                    {
                        if (DevMsgUtil.ConfirmYesNo(checkResult + ",是否继续导入！") != DialogResult.Yes)
                        {
                            return;
                        }
                        else
                        {
                            continue;
                        }
                    }
                    NcovUsers ncovUser = new NcovUsers();
                    ncovUser.PAT_SEQ = ncovUsersService.GetHisMaxId("NCOV_USERS", "PAT_SEQ");
                    ncovUser.PAT_NM = dt.Rows[i][1].ToString();//2-姓名
                    ncovUser.CHT_ID = dt.Rows[i][2].ToString();//3-门诊号码
                    ncovUser.ID_NO = dt.Rows[i][3].ToString();//4-身份证号
                    ncovUser.BIRTHDAY = Globals.GetBirthByIdNo(ncovUser.ID_NO);
                    ncovUser.SEX = Globals.GetSexByIdNo(ncovUser.ID_NO);
                    ncovUser.TELPHONE = dt.Rows[i][4].ToString();//5-联系电话
                    ncovUser.COMPANY = dt.Rows[i][5].ToString();//6-单位
                    ncovUser.DEPARTMENT = dt.Rows[i][6].ToString();//7部门
                    ncovUser.PAT_TYPE = dt.Rows[i][7].ToString();//8-检测对象类型
                    ncovUser.PAT_TAGS = dt.Rows[i][8].ToString();//9-患者标记
                    ncovUser.DC_FLAG = "0";//默认启用
                    ncovUsers.Add(ncovUser);
                }
            }

            if (ncovUsers.Count > 0)
            {
                if (ncovUsersService.ImportUsers(ncovUsers))
                {
                    Globals.ShowTips("导入成功！");
                    QueryData();
                }
            }
        }

        private string CheckExcelRow(DataRow dataRow, int rowIndex)
        {
            if (string.IsNullOrEmpty(dataRow[1].ToString()))
            {
                return string.Format("第{0}行,姓名为空", rowIndex);
            }
            if (string.IsNullOrEmpty(dataRow[3].ToString()))
            {
                return string.Format("第{0}行,身份证号为空", rowIndex);
            }
            if (string.IsNullOrEmpty(dataRow[7].ToString()))
            {
                return string.Format("第{0}行,检测对象类型为空", rowIndex);
            }
            return "";
        }

        private void bbiAdd_ItemClick(object sender, ItemClickEventArgs e)
        {
            //新增
            FrmNcovPatEdit frmMenuEdit = new FrmNcovPatEdit();
            frmMenuEdit.OnDataSaved += FrmMenuEdit_OnDataSaved;
            frmMenuEdit.ShowDialog();
        }

        private void FrmMenuEdit_OnDataSaved(object sender, EventArgs e)
        {
            QueryData();
        }

        private void bbiEdit_ItemClick(object sender, ItemClickEventArgs e)
        {
            EditNcovUser();
        }

        private void EditNcovUser()
        {
            if (gvData.FocusedRowHandle >= 0)
            {
                FrmNcovPatEdit frmMenuEdit = new FrmNcovPatEdit();
                var ncovUser = gvData.GetRow(gvData.FocusedRowHandle) as NcovUsers;
                frmMenuEdit.ID = ncovUser.PAT_SEQ.ToString();
                List<string> ids = new List<string>();
                for (int i = 0; i < gvData.RowCount; i++)
                {
                    ids.Add((gvData.GetRow(i) as NcovUsers).PAT_SEQ.ToString());
                }
                frmMenuEdit.IDList = ids;
                frmMenuEdit.OnDataSaved += FrmMenuEdit_OnDataSaved;
                frmMenuEdit.ShowDialog();
            }
        }

        private void gcData_DoubleClick(object sender, EventArgs e)
        {
            EditNcovUser();
        }

        private void bbiAbandon_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (gvData.FocusedRowHandle >= 0)
            {
                var ncovUser = gvData.GetRow(gvData.FocusedRowHandle) as NcovUsers;
                if (Globals.ShowYesNoAndTips("您正在作废名为" + ncovUser.PAT_NM + "的核酸采集对象！是否继续？") == DialogResult.Yes)
                {
                    if (ncovUsersService.AbandonUser(ncovUser))
                    {
                        Globals.ShowTips("作废成功！");
                        QueryData();
                    }
                }
            }
        }
    }
}